﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SSE657.BahMap.Common;
using System.IO;
using System.Security.Principal;

namespace SSE657.BahMap.DataAccess.Text
{
    public abstract class TextDataConnectorBase
    {
        protected string _rootDirectory;

        protected Dictionary<string, Area> _mhaAreas;

        public TextDataConnectorBase()
        {
            // TODO: change this to dynamically pull file from AppData or something
            this._rootDirectory = GetRootDirectory();

            this._mhaAreas = new Dictionary<string, Area>();
            LoadAreas(); // thread this?
        }

        protected virtual string GetRootDirectory()
        {
            string currDir = Environment.CurrentDirectory; // works from test, doesn't work from web
            int index = currDir.IndexOf("SSE657.BahMap");
            if (index >= 0)
                return Path.Combine(currDir.Substring(0, index + 14), @"data");
            else // Cheating! Go hard or go home! =/
            {
                string userName = WindowsIdentity.GetCurrent().Name;
                int i = userName.LastIndexOf('\\');
                if (i >= 0)
                    userName = userName.Substring(i + 1, userName.Length - i - 1);
                return String.Format(@"C:\Users\{0}\Documents\Visual Studio 2010\Projects\SSE657.BahMap\data",
                    userName);
            }
        }

        protected virtual void LoadAreas()
        {
            Dictionary<string, HashSet<int>> areas = new Dictionary<string, HashSet<int>>();
            
            // parse data from text file
            string filename = "sorted_zipmha12.txt";
            StreamReader file = new StreamReader(Path.Combine(_rootDirectory + @"\BAH2012", filename));
            string line = file.ReadLine();
            while (line != null)
            {
                string[] words = line.Split(' ');
                if (!areas.ContainsKey(words[1]))
                    areas.Add(words[1], new HashSet<int>());
                int zip = int.Parse(words[0]);
                areas[words[1]].Add(zip);
                line = file.ReadLine();
            }

            // convert to Areas
            foreach (string key in areas.Keys)
            {
                _mhaAreas.Add(key, new Area() { MHA = key, ZIPs = areas[key]});
            }
        }
    }
}
